package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.dto.YDDto;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.YDDDApi;
import com.ruoyi.system.outto.game.YDDDV2Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/7/26 10:22
 */
@Slf4j
@Service
public class YDDDV2APIimpl implements YDDDV2Api {

    @Resource
    private CommonApi commonApi;
    @Resource
    private InfoImgMapper infoImgMapper;

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Value("${desc.title}")
    private String descTitle;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        Map<String, Object> result = new HashMap<>();

        if (sa.getSaleName().contains("YDD_H")){
            accountInfo = corverUser(accountInfo);
        }

        List<YDDto> yds = new ArrayList<>();
        YDDto yd = new YDDto();
        BeanUtils.copyProperties(accountInfo,yd);
        yd.setOrderNo(descTitle+accountInfo.getId());
        yd.setDes(accountInfo.getDes());
        yd.setExtractAccount(descTitle+accountInfo.getId());

        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(),  sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(), sa);
        yd.setPrice(bigDecimal);
//        yd.setNewPrice(accountInfo.getNewPrice());


        String uuid = UUIDGenerator.generate12();
        yd.setUuid(uuid);

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType("1");
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String images = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        yd.setImgList(images);
        yds.add(yd);


        /**
         * 查询合作伙伴相关信息
         */
//        SalePartner sa = commonApi.get(LCConstant.saleNameYDD,userId);
//        if (Objects.isNull(sa)){
//            throw new GlobalException("合作伙伴未查到");
//        }

        Map<String,String> header = new HashMap<>();
        header.put("author",sa.getSaleKey());
        log.info("虞都添加接口请求参数={}", JSONObject.toJSONString(yds));
        String response = null;
        try {
//            response = HttpClientUtils.sendPostRequest(sa.getThreeOther()+ "/api/account/save", JSONObject.toJSONString(yds),header);
             response = HttpUtils.sendYDPost(sa.getThreeOther() + "/api/account/save", JSONObject.toJSONString(yds), sa.getSaleKey());
        } catch (Exception e) {
            log.info(e.getMessage());
            result.put("code",500);
            result.put("req",JSONObject.toJSONString(yds));
            result.put("res",e.getMessage());
            result.put("msg",e.getMessage());
            return AjaxResult.success(result);
        }
        log.info("虞都添加接口返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"200".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
//            {
//                "msg": "操作成功",
//                    "code": 200,
//                    "data": {
//                "accountId": "7897"
//            }
//            }
            JSONObject jsonObject = JSONObject.parseObject(response);
            JSONObject data = jsonObject.getJSONObject("data");
            Long accountId = data.getLong("accountId");
            AccountInfo info = accountInfoMapper.selectAccountInfoById(accountInfo.getId());
            info.setYdid(accountId);
            accountInfoMapper.updateAccountInfo(info);
        }

        result.put("req",JSONObject.toJSONString(yds));
        result.put("res",response);
        result.put("msg",resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        Map<String, Object> result = new HashMap<>();
        if (sa.getSaleName().contains("YDD_H")){
            accountInfo = corverUser(accountInfo);
        }
        YDDto yd = new YDDto();
        BeanUtils.copyProperties(accountInfo,yd);
        yd.setId(accountInfo.getId());
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(),  sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(), sa);
        yd.setPrice(bigDecimal);
//        yd.setNewPrice(accountInfo.getNewPrice());

        yd.setOrderNo(descTitle+accountInfo.getId());
        yd.setDes(accountInfo.getDes());
        yd.setExtractAccount(descTitle+accountInfo.getId());
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType("1");
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String images = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        yd.setImgList(images);

        /**
         * 查询合作伙伴相关信息
         */
//        SalePartner sa = commonApi.get(LCConstant.saleNameYDD,userId);
//        if (Objects.isNull(sa)){
//            throw new GlobalException("合作伙伴未查到");
//        }
        Map<String,String> header = new HashMap<>();
        header.put("author",sa.getSaleKey());
        log.info("虞都编辑接口请求参数={}", JSONObject.toJSONString(yd));
        String response = null;
        try {
//            response = HttpClientUtils.sendYDPost(sa.getThreeOther()+ "/api/account/edit", JSONObject.toJSONString(yd),header);
            response = HttpUtils.sendYDPost(sa.getThreeOther() + "/api/account/edit", JSONObject.toJSONString(yd), sa.getSaleKey());
        } catch (Exception e) {
            log.info(e.getMessage());
            result.put("code",200);
            result.put("req",JSONObject.toJSONString(yd));
            result.put("res",e.getMessage());
            result.put("msg",e.getMessage());
            return AjaxResult.success(result);
        }
        log.info("虞都编辑接口返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"200".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(yd));
        result.put("res",response);
        result.put("msg",resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(Long id, Long userId, SalePartner sa) {
        Map<String, Object> result = new HashMap<>();
        /**
         * 查询合作伙伴相关信息
         */
//        SalePartner sa = commonApi.get(LCConstant.saleNameYDD,userId);
//        if (Objects.isNull(sa)){
//            throw new GlobalException("合作伙伴未查到");
//        }

        Map<String,String> params = new HashMap<>();
        Map<String,String> header = new HashMap<>();
        header.put("author",sa.getSaleKey());
        params.put("id",id.toString());
        log.info("虞都编辑删除请求参数={}", JSONObject.toJSONString(params));
        String response = null;
        try {
//            response = HttpClientUtils.sendPostRequest(sa.getThreeOther()+ "/api/account/undercarriage", JSONObject.toJSONString(params),header);
            response = HttpUtils.sendYDPost(sa.getThreeOther() + "/api/account/undercarriage", JSONObject.toJSONString(params), sa.getSaleKey());
        } catch (Exception e) {
            log.info(e.getMessage());
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",e.getMessage());
            result.put("msg",e.getMessage());
            return AjaxResult.success(result);
        }
        log.info("虞都删除接口返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"200".equals(resultJson.getString("code"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    private AccountInfo corverUser(AccountInfo accountInfo){

//        安卓微信 安卓QQ  苹果微信 苹果QQ

        if (Objects.equals("安卓WX",accountInfo.getRegional())){
            accountInfo.setRegional("安卓微信");
        }
        if (Objects.equals("安卓Q",accountInfo.getRegional())){
            accountInfo.setRegional("安卓QQ");
        }
        if (Objects.equals("苹果WX",accountInfo.getRegional())){
            accountInfo.setRegional("苹果微信");
        }
        if (Objects.equals("苹果Q",accountInfo.getRegional())){
            accountInfo.setRegional("苹果QQ");
        }
        if (Objects.equals("有二次",accountInfo.getLevel())){
            accountInfo.setLevel("可实名");
        }
        if (Objects.equals("无二次",accountInfo.getLevel())){
            accountInfo.setLevel("包人脸");
        }
        return accountInfo;

    }

}
